package com.san.warnings.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.san.base.dao.BaseManager;
import com.san.common.datasource.JdbcManager;
import com.san.common.utils.Constant;
import com.san.common.utils.MD5Utils;
import com.san.common.utils.Query;
import com.san.warnings.domain.WarningsCompanyDO;

@Service
public class WarningsManager extends BaseManager {

	private static final Logger logger = LoggerFactory.getLogger(WarningsManager.class);

	/**
	 * 删除对应的预警企业
	 * 
	 * @param warnId
	 * @param deptId
	 * @return
	 */
	public boolean batchRemoveData(Long warnId, Long deptId) {
		JdbcManager jdbcManager = new JdbcManager();
		StringBuffer sql = new StringBuffer();
		sql.append("DELETE FROM result_warning WHERE warn_id = ? AND dept_id = ?");
		Object[] obj = { warnId, deptId };
		boolean countResult = false;
		try {
			countResult = jdbcManager.executeSQL(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE), sql.toString(),
					obj);
		} catch (Exception e) {
			logger.error("获取数据库连接失败", e);
		}
		return countResult;
	}
	
	public List<WarningsCompanyDO> listMyFollowDetail(Query query) {
		JdbcManager jdbcManager = new JdbcManager();
		String companyName = (String) query.get("companyName");
		Long deptId = (Long) query.get("deptId");
		String warnId = (String) query.get("warnId");
		Integer offset = (Integer) query.get("offset");
		Integer limit = (Integer) query.get("limit");
		Long status = (Long) query.get("status");
		Object[] obj = { offset, limit };
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT\r\n").append("	id,\r\n").append("	company_name,\r\n").append("	uscc,\r\n")
				.append("	legal_person_id,\r\n").append("	status\r\n").append("FROM\r\n")
				.append("	result_warning\r\n").append("WHERE 1=1 \r\n");
		if (companyName != null && !"".equals(companyName)) {
			sql.append("	AND company_name = " + companyName + "\r\n");
		}
		if (deptId != null) {
			sql.append("	AND dept_id = " + deptId + "\r\n");
		}
		if (warnId != null && !"".equals(warnId)) {
			sql.append("	AND warn_id = " + warnId + "\r\n");
		}
		if (status != null) {
			sql.append("	AND status = " + status + "\r\n");
		}
		sql.append("limit ?,?");
		List<Map<String, Object>> result = null;
		try {
			result = jdbcManager.executeQuery(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE), sql.toString(),
					obj);
		} catch (Exception e) {
			logger.error("获取数据库连接失败", e);
		}
		List<WarningsCompanyDO> resultList = new ArrayList<WarningsCompanyDO>();
		if (null != result) {
			for (Map<String, Object> resultMap : result) {
				WarningsCompanyDO warningsCompanyDO = new WarningsCompanyDO();
				warningsCompanyDO.setId(((Integer) resultMap.get("id")));
				warningsCompanyDO.setCompanyName((String) resultMap.get("company_name"));
				warningsCompanyDO.setUscc((String) resultMap.get("uscc"));
				warningsCompanyDO.setLegalPersonId((String) resultMap.get("legal_person_id"));
				warningsCompanyDO.setStatus((Integer) resultMap.get("status"));
				resultList.add(warningsCompanyDO);
			}
		}
		return resultList;
	}

	public Long CountMyFollowDetail(Long warnId, Long deptId) {
		JdbcManager jdbcManager = new JdbcManager();
		Object[] obj = {};
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT\r\n").append("	count(1) count\r\n").append("FROM\r\n")
				.append("	result_warning\r\n").append("WHERE 1=1 \r\n").append("	AND status = 0\r\n");
		if (deptId != null) {
			sql.append("	AND dept_id = " + deptId + "\r\n");
		}
		if (warnId != null) {
			sql.append("	AND warn_id = " + warnId + "\r\n");
		}
		List<Map<String, Object>> countResult = null;
		try {
			countResult = jdbcManager.executeQuery(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE),
					sql.toString(), obj);
		} catch (Exception e) {
			logger.error("获取数据库连接失败", e);
		}
		Long count = null;
		for (Map<String, Object> countMap : countResult) {
			count = (Long) countMap.get("count");
		}
		return count;
	}

	public Map<String,Object> batchAddData(Long warnId, Long deptId, List<List<String>> datas) {
		// TODO: 数据写入方式 可改为批量 待优化
		JdbcManager jdbcManager = new JdbcManager();
		StringBuffer sql = new StringBuffer();
		sql.append(
				"insert into result_warning (company_name,uscc,legal_person_id,dept_id,warn_id) values (?,?,?,?,?)");
		// 失败数量
		int errorCount = 0;
		// 重复数量
		int duplicateCount = 0;
		// 成功数量
		int successCount = 0;
		WarningsCompanyDO warningsCompanyDO;
		for (List<String> data : datas) {
			warningsCompanyDO = new WarningsCompanyDO();
			warningsCompanyDO.setCompanyName(data.get(0));
			if(data.size() >=2) {
			warningsCompanyDO.setUscc(data.get(1));
			}
			warningsCompanyDO.setLegalPersonId(MD5Utils.MD5Encode(data.get(0)));
			warningsCompanyDO.setDeptId(deptId);
			warningsCompanyDO.setWarnId(warnId);
			Object[] obj = { warningsCompanyDO.getCompanyName(), warningsCompanyDO.getUscc(), warningsCompanyDO.getLegalPersonId(), warningsCompanyDO.getDeptId(),
					warningsCompanyDO.getWarnId() };
			try {
				String testSql = "select count(1) as count from result_warning where company_name = ? and uscc = ? and legal_person_id = ? and dept_id = ? and warn_id = ?";
				List<Map<String, Object>> list = jdbcManager.executeQuery(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE),
						testSql, obj);
				Long count = Long.valueOf(String.valueOf(list.get(0).get("count")));
				if(count <= 0) {
					jdbcManager.executeSQL(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE),
							sql.toString(), obj);
					successCount++;
				}else {
					duplicateCount++;
				}
			} catch (Exception e) {
				logger.error("获取数据库连接失败", e);
				errorCount++;
			}
		}
		Map<String,Object> resultMap = new HashMap<String, Object>();
		resultMap.put("errorCount", errorCount);
		resultMap.put("duplicateCount", duplicateCount);
		resultMap.put("successCount", successCount);
		return resultMap;
	}

	public int CountMyFollowDetail(Query query) {
		JdbcManager jdbcManager = new JdbcManager();

		String companyName = (String) query.get("companyName");
		Long deptId = (Long) query.get("deptId");
		String warnId = (String) query.get("warnId");
		Long status = (Long) query.get("status");
		Object[] obj = {};
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT\r\n").append("	count(1) count\r\n").append("FROM\r\n")
				.append("	result_warning\r\n").append("WHERE 1=1 \r\n");
		if (companyName != null && !"".equals(companyName)) {
			sql.append("	AND company_name = " + companyName + "\r\n");
		}
		if (deptId != null) {
			sql.append("	AND dept_id = " + deptId + "\r\n");
		}
		if (warnId != null && !"".equals(warnId)) {
			sql.append("	AND warn_id = " + warnId + "\r\n");
		}
		if (status != null) {
			sql.append("	AND status = " + status + "\r\n");
		}
		List<Map<String, Object>> countResult = null;
		try {
			countResult = jdbcManager.executeQuery(this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE),
					sql.toString(), obj);
		} catch (Exception e) {
			logger.error("获取数据库连接失败", e);
		}
		Long count = null;
		for (Map<String, Object> countMap : countResult) {
			count = (Long) countMap.get("count");
		}
		int total = Integer.valueOf(count.toString());
		return total;
	}

}
